package com.online.pay.common.sign;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

import com.online.pay.common.modle.Contains;

/**
 * 支付宝签名验签工具
 * 
 * @author Qiurz
 *
 */
public class AlipaySignature {

	/**
	 * @param content
	 *            待签名字符串
	 * @param privateKey
	 *            加签私钥
	 **/
	public static String rsaSign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance(Contains.ALI_SIGN_TYPE);
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);
			Signature signature = Signature.getInstance(Contains.SIGN_ALGORITHMS);
			signature.initSign(priKey);
			signature.update(content.getBytes(Contains.CHARSET));
			byte[] signed = signature.sign();
			return Base64Util.encode(signed);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 此方法会去掉sign_type做验签，暂时除生活号（原服务窗）激活开发者模式外都使用V1。
	 * 
	 * @param params
	 *            参数列表(包括待验签参数和签名值sign) key-参数名称 value-参数值
	 * @param publicKey
	 *            验签公钥
	 **/
	public static boolean rsaCheckV1(Map<String, String> params, String publicKey) {
		String signValue = params.remove("sign");
		String signStr = KeyValueUtil.mapToString(params);
		try {
			X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64Util.decode(publicKey));
			KeyFactory keyFactory = KeyFactory.getInstance(Contains.ALI_SIGN_TYPE);
			PublicKey publiKey = keyFactory.generatePublic(x509EncodedKeySpec);
			Signature signature = Signature.getInstance(Contains.SIGN_ALGORITHMS);
			signature.initVerify(publiKey);
			signature.update(signStr.getBytes(Contains.CHARSET));
			return signature.verify(Base64Util.decode(signValue));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
